package com.item.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.JSONUtils;
import com.base.util.StringUtil;
import com.item.dao.model.Category;
import com.item.dao.model.CategoryExample;
import com.item.exception.JSONRepUtils;
import com.item.service.CategoryService;

@Controller
public class CategoryController {
	@Autowired
	private CategoryService categoryService;
	
	@RequestMapping("/listCategory")
	@ResponseBody
	public String list(Page param, Category category, Integer isNotPage, Integer isM) throws Exception{
		Object objForSer = null;
		CategoryExample example = new CategoryExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		CategoryExample.Criteria criteria = example.createCriteria();
		if(StringUtils.isNotBlank(category.getPid())) {
			criteria.andPidEqualTo(category.getPid());
		}
		example.setOrderByClause("code ASC");
		List<Category> list = categoryService.selectByExample(example);

		if(isNotPage != null && isNotPage == 1) {
			objForSer = list;
		} else {
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		}
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/showlistCategory")
	public String list() {
		return "category/categoryList";
	}
	
	@RequestMapping("/toEditCategory")
	public String toEdit()throws Exception{
		return "category/categoryEdit";
	}
	
	@RequestMapping(value="/saveCategory")
	@ResponseBody
	public String save(Category category, Integer isTop, HttpSession session) throws Exception{		
		try{
			if(StringUtil.isEmpty(category.getId())){
				category.setCode(categoryService.getLeastCode(category.getPid()));
				
				category.setCreateTime(new Date());
				categoryService.insertSelective(category);
			} else {
				category.setModifyTime(new Date());
				categoryService.updateByPrimaryKeySelective(category);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	
	@RequestMapping(value="/findByIdCategory")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		Category n = categoryService.selectByPrimaryKey(id);

		return JSONUtils.serialize(n);
	}
	
	@RequestMapping("/delCategory")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			categoryService.deleteByPrimaryKey(ids[i]);
		}
		return "{\"success\":true}";
	}
	
	
}

